import {config} from "../config.js"

const tips = {
  1: '抱歉出现了一个错误',
  1005: 'token无效，请重新登陆',
}

class HTTP {
  constructor() {
    this.baseRestUrl = config.api_blink_url
  }

  request({url,data={},method='GET'}){
    return new Promise((resolve,reject)=>{
      this._request(url, resolve, reject, data, method)
    })
  }

  _request(url, resolve, reject, data = {}, method = 'GET') {
    let _this = this;
    let currentUrl = this.baseRestUrl + url;
    wx.request({
      url: currentUrl,
      data: data,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      method: method,
      success: function(res) {
        console.log(res)
        // 判断以2（2xx)开头的状态码为正确
        // 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
        const code = res.statusCode.toString();
        const startChar = code.charAt(0);
        if (startChar == '2' && res.data.code == 0) {
          resolve(res.data);
        } else if (res.data.code == 403) {
          wx.hideLoading()
          //跳转到登陆页面
          wx.navigateTo({
            url: '/pages/login/index'
          })
        }else if (startChar == '2' && res.data.code == -1){
          reject()
          wx.hideLoading()
          wx.showToast({
            title:res.data.msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          reject()
          wx.hideLoading()
          // params.error && params.error(res);
          _this._show_error(res.data.code)
        }
      },
      fail: function(res) {
        reject()
        wx.hideLoading()
        _this._show_error(1)
      }
    })
  }

  _show_error(error_code) {
    if (!error_code) {
      error_code = 1;
    }
    const tip = tips[error_code]
    wx.showToast({
      title: tip ? tip : tips[1],
      icon: 'none',
      duration: 2000
    })
  }

}

export { HTTP };
